/**
 * 常用原生服务
 * 1. 网络状态
 * 2. 文件下载
 * 3. 屏幕常亮
 */

import { Injectable } from '@angular/core';
import { Platform, ToastController } from '@ionic/angular';
import { GlobalService } from './global.service';
import { Insomnia } from '@ionic-native/insomnia/ngx';
import { Network } from '@ionic-native/network/ngx';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class NativeService {
  alarmInterval; // 告警语音播报定时器


  headimgurl: String;
  toast;
  public jpushSubject: Subject<any> = new Subject<any>();
  public setSubject: Subject<any> = new Subject<any>();
  public jpushService: Subject<any> = new Subject<any>();
  private isOffline = false;

  constructor(
    public platform: Platform,
    public globalservice: GlobalService,
    private insomnia: Insomnia,
    private toastCtrl: ToastController,
    private transfer: FileTransfer,
    private network: Network
  ) { }

  public get jpushMonitor(): Observable<any> {
    return this.jpushSubject.asObservable();
  }

  public get jpushServices(): Observable<any> {
    return this.jpushService.asObservable();
  }

  getPlatformType() {
    let ptype = 'web';
    if (this.platform.is('ios')) {
      ptype = 'ios';
    }
    if (this.platform.is('android')) {
      ptype = 'android';
    }

    return ptype;
  }

  listenJPushInfo() {
    document.addEventListener(
      'jpush.openNotification',
      (event: any) => {
        let content;
        if (this.getPlatformType() === 'android') {
          content = event.alert;
        } else {
          // iOS
          if (event.aps === undefined) {
            // 本地通知
            content = event.content;
          } else {
            // APNS
            content = event.aps.alert;
          }
        }
        console.log('open notification: ' + JSON.stringify(event));
        this.jpushSubject.next(event);
      },
      false
    );

    document.addEventListener(
      'jpush.receiveNotification',
      (event: any) => {
        let content;
        if (this.platform.is('android')) {
          content = event.alert;
        } else {
          content = event.aps.alert;
        }
        // console.log('Receive notification: ' + JSON.stringify(event));
        this.jpushService.next(event);
      },
      false
    );

    // document.addEventListener(
    //   'jpush.receiveLocalNotification',
    //   (event: any) => {
    //     // iOS(*,9) Only , iOS(10,*) 将在 jpush.openNotification 和 jpush.receiveNotification 中触发
    //     let content;
    //     if (this.devicePlatform === 'Android') {
    //     } else {
    //       content = event.content;
    //     }
    //     console.log('receive local notification: ' + JSON.stringify(event));
    //   },
    //   false
    // );
  }

  /**
   * 初始化 Native 服务
   */
  initNativeService() {
    this.listenInsomniaState();
    this.listenNetworkState();
  }

  /**
   * 监听屏幕显示状态
   */
  listenInsomniaState() {
    if (this.globalservice.isAlwaysLight) {
      this.insomnia
        .keepAwake()
        .then(
          () => console.log('insomnia init success'),
          e => console.log('insomnia init error', e)
        );
    }
  }

  /**
   * 监听网络状态
   */
  listenNetworkState() {
    this.createToast();
    const offlineOnlineThrottle = this.throttle(msg => {
      if (this.isOffline === true) {
        this.toast.message(msg);
        this.toast.present();
      }
    }, 2400);
    this.network.onDisconnect().subscribe(() => {
      this.isOffline = true;
      console.log('network was disconnected :-(');
      offlineOnlineThrottle('网络已断开！');
    });

    this.network.onConnect().subscribe(() => {
      console.log('network connected!');
      this.isOffline = false;
      this.toast.dismiss();
      setTimeout(() => {
        if (this.network.type === 'wifi') {
          console.log('got network:wifi!');
        }
      }, 3000);
    });
  }

  /**
   * 函数节流方法
   * @param Function fn 延时调用函数
   * @param Number delay 延迟多长时间
   * @return Function 延迟执行的方法
   */
  throttle(fn, delay) {
    let timer = null;
    return function (msg) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn(msg);
      }, delay);
    };
  }

  /**
   * 显示消息
   * @param msg 消息
   */
  async createToast() {
    this.toast = await this.toastCtrl.create({
      message: '',
      duration: 3000,
      position: 'top',
      cssClass: 'my-toast-style',
      showCloseButton: true,
      closeButtonText: '关闭',
      // dismissOnPageChange: true,
    });
  }

  /**
   * 文件下载
   * @param remotepath  远程路径
   * @param targetPathWithFileName 带文件名的下载地址
   */
  filedownload(remotepath, targetPathWithFileName, isToURL?) {
    return new Promise((resolve, reject) => {
      const options = {
        headers: {
          Authorization: this.globalservice.token,
        },
      };
      const trustHosts = true;
      console.log(remotepath, targetPathWithFileName, trustHosts, options)
      const fileTransfer: FileTransferObject = this.transfer.create();
      fileTransfer
        .download(remotepath, targetPathWithFileName, trustHosts, options)
        .then(result => {
          console.log('filedownload： 下载完成..');
          resolve(isToURL ? result.nativeURL : result.toURL());
        })
        .catch(err => {
          reject('ERR:下载出错');
          console.log('filedownload： 下载出错', err);
        });
      fileTransfer.onProgress((evt: ProgressEvent) => {
        console.log(evt);
      });
    });
  }

  /**
   * 文件上传
   * @param fileUrl    文件路径
   * @param remotepath 远程路径
   */
  fileUpload(fileUrl, remotepath, options) {
    return new Promise((resolve, reject) => {
      const fileTransfer: FileTransferObject = this.transfer.create();
      fileTransfer.upload(fileUrl, remotepath, options)
        .then((data) => {
          console.log('fileUpload 上传完成..');
          resolve(data);
        }, (err) => {
          reject('ERR:上传出错');
          console.log('fileUpload 上传出错..');
        });
    });
  }

}
